import requests
import json
from typing import List, Dict

class FeishuBitableReader:
    def __init__(self, app_id: str, app_secret: str):
        """
        初始化飞书多维表格读取器
        
        :param app_id: 飞书应用的App ID
        :param app_secret: 飞书应用的App Secret
        """
        self.app_id = app_id
        self.app_secret = app_secret
        self.tenant_access_token = None

    def _get_tenant_access_token(self) -> str:
        """
        获取租户访问令牌
        
        :return: 租户访问令牌
        """
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal"
        payload = {
            "app_id": self.app_id,
            "app_secret": self.app_secret
        }
        headers = {'Content-Type': 'application/json'}
        
        try:
            response = requests.post(url, headers=headers, json=payload)
            response.raise_for_status()
            data = response.json()
            
            if data.get('code') != 0:
                raise Exception(f"获取访问令牌失败: {data.get('msg')}")
            
            self.tenant_access_token = data['tenant_access_token']
            return self.tenant_access_token
            
        except Exception as e:
            raise Exception(f"获取租户访问令牌出错: {str(e)}")

    def get_all_records(self, app_token: str, table_id: str, view_id: str = None, page_size: int = 500) -> List[Dict]:
        """
        获取多维表格中的所有记录
        
        :param app_token: 多维表格的app_token
        :param table_id: 表格ID
        :param view_id: 视图ID(可选)
        :param page_size: 每页记录数(最大500)
        :return: 包含所有记录的列表
        """
        if not self.tenant_access_token:
            self._get_tenant_access_token()
        
        url = f"https://open.feishu.cn/open-apis/bitable/v1/apps/{app_token}/tables/{table_id}/records/search"
        headers = {
            'Content-Type': 'application/json',
            'Authorization': f'Bearer {self.tenant_access_token}'
        }
        
        all_records = []
        page_token = ''
        has_more = True
        
        while has_more:
            try:
                params = {
                    "page_size": min(page_size, 500),
                    "page_token": page_token
                }
                
                if view_id:
                    params["view_id"] = view_id
                
                response = requests.post(url, headers=headers, json=params)
                response.raise_for_status()
                data = response.json()
                
                if data.get('code') != 0:
                    # 如果token过期，尝试刷新一次
                    if data.get('code') == 99991668:
                        self._get_tenant_access_token()
                        headers['Authorization'] = f'Bearer {self.tenant_access_token}'
                        continue
                    raise Exception(f"API错误: {data.get('msg')}")
                
                items = data.get('data', {}).get('items', [])
                all_records.extend(items)
                
                has_more = data.get('data', {}).get('has_more', False)
                page_token = data.get('data', {}).get('page_token', '')
                
                print(f"已获取 {len(all_records)} 条记录...")
                
            except Exception as e:
                raise Exception(f"获取记录出错: {str(e)}")
        
        return all_records

    def save_to_json(self, data: List[Dict], filename: str):
        """
        将数据保存为JSON文件
        
        :param data: 要保存的数据
        :param filename: 文件名
        """
        with open(filename, 'w', encoding='utf-8') as f:
            json.dump(data, f, indent=2, ensure_ascii=False)

def main():
    # 根据您提供的信息配置
    APP_ID = "cli_a80b214821bcd01c"
    APP_SECRET = "Nqxyj4B3NX8A5qdZvEyRPca4z1DoLYDo"
    
    # 从您的表格链接中提取的参数
    APP_TOKEN = "MLZMbVLBhaBf43skxedcYtl7nwf"  # base/后面的部分
    TABLE_ID = "tblrKbRVWERKeK8H"             # table=后面的部分
    VIEW_ID = "vewJvklNKS"                   # view=后面的部分
    
    # 输出文件名
    OUTPUT_FILE = "消息汇总.json"
    
    try:
        print("开始获取飞书多维表格数据...")
        
        # 创建读取器实例
        reader = FeishuBitableReader(APP_ID, APP_SECRET)
        
        # 获取所有记录
        records = reader.get_all_records(APP_TOKEN, TABLE_ID, VIEW_ID)
        
        print(f"成功获取 {len(records)} 条记录")
        
        # 保存到JSON文件
        reader.save_to_json(records, OUTPUT_FILE)
        print(f"数据已保存到 {OUTPUT_FILE}")
        
        # 打印前几条记录示例
        print("\n示例数据(前3条):")
        for i, record in enumerate(records[:3]):
            print(f"\n记录 {i+1}:")
            print(json.dumps(record, indent=2, ensure_ascii=False))
        
    except Exception as e:
        print(f"程序运行出错: {str(e)}")

if __name__ == '__main__':
    main()